#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import datetime
import urllib.request

import cssutils
from bs4 import BeautifulSoup


def downBingImg(url):
    res = urllib.request.urlopen(url)
    soup =BeautifulSoup(res, "html.parser")

    # 获取下载链接
    downloadUrl = parse_style_attribute(soup.select(".img_cont")[0].get('style'))
    #downloadUrl = url + downloadUrl
    print("downloadUrl:>>> " + downloadUrl)

    # 获取背景图片名称
    imageName = soup.select(".musCardCont .title")[0].text;
    imageName = datetime.datetime.now().strftime('%Y-%m-%d') + " " + imageName

    print(imageName + ":>>> " + downloadUrl)
    # 下载图片
    urllib.request.urlretrieve(downloadUrl, '/mnt/c/Users/Think/Pictures/Saved Pictures/%s.jpg' % imageName)

# 从background-image: url('**') 提取url
def parse_style_attribute(style_string):
    sheet = cssutils.css.CSSStyleSheet()
    
    #删除与url无关的style
    style_string = style_string.split(";")[0]
    sheet.add("dummy_selector { %s }" % style_string)
    
    url = list(cssutils.getUrls(sheet))[0]
    return url

if __name__ == '__main__':
    url = 'https://cn.bing.com/'
    downBingImg(url)
